#include <iostream>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

// Fater process -> read
// Child process -> write
int main()
{
    // 创建管道
    int fds[2] = {0};
    int n = pipe(fds); // fds：输出型参数
    if (n != 0)
    {
        std::cerr << "pipe error" << std::endl;
        return 1;
    }

    // Fater process -> read
    // Child process -> write
    // 创建子进程
    pid_t id = fork();
    if(id < 0)
    {
        std::cerr<<"fork error"<<std::endl;
        return 2;
    }
    else if (id == 0)
    {
        //子进程
        //关闭不需要的fd，关闭read
        close(fds[0]);

        int cnt = 0;
        //int total = 0;
        while(true)
        {
            //std::string message = "h";
            std::string message = "hello bit,hello ";
            message += std::to_string(getpid());
            message += ",";
            message += std::to_string(cnt);

            ::write(fds[1],message.c_str(),message.size());
            //total += ::write(fds[1],message.c_str(),message.size());
            cnt++;
            //std::cout<<"total:"<<total<<std::endl;
            sleep(1);

            //break;
        }
        
        exit(0);
    }
    else
    {
        //父进程
        //关闭不需要的fd，关闭write
        close(fds[1]);

        char buffer[1024];
        while(true)
        {
            sleep(1);
            size_t n = ::read(fds[0],buffer,sizeof(buffer));
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout<<"child->father,message:"<<buffer<<std::endl;
            }
            else if(n == 0)
            {
                std::cout<<"n:"<<n<<std::endl;
                std::cout<<"child quit??? me too"<<std::endl;
            }

            close(fds[0]);
            break;
        }

        int status = 0;
        pid_t rid = waitpid(id,&status,0);
        std::cout<<std::endl;
        std::cout<<"father wait child success:"<<rid<<"exit code:"<<
        ((status<<8)&0xFF)<<", exit sig："<<(status & 0x7F)<<std::endl;
    }

    return 0;
}
